package org.yunai.yfserver.server;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.yunai.yfserver.common.LoggerFactory;
import org.yunai.yfserver.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * JVM停止时的钩子类
 * User: yunai
 * Date: 13-4-27
 * Time: 下午6:44
 */
public class ShutdownHooker implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.Logger.server,
            ShutdownHooker.class);

    /**
     * 停止时执行的钩子
     */
    private final List<Runnable> hookers;

    public ShutdownHooker() {
        this.hookers = new ArrayList<Runnable>(1);
    }

    /**
     * 添加钩子
     * @param runnable 钩子
     * @return 添加结果
     */
    public boolean add(Runnable runnable) {
        Assert.isTrue(runnable != this, "can't add self.");

        return !this.hookers.contains(runnable) && this.hookers.add(runnable);
    }

    /**
     * 移除钩子
     * @param runnable 钩子
     * @return 移除结果
     */
    public boolean remove(Runnable runnable) {
        return hookers.remove(runnable);
    }

    /**
     * 执行钩子们
     */
    @Override
    public void run() {
        LOGGER.info("[run] [ShutdownHooker run].");
        try {
            for (Runnable hook : hookers) {
                hook.run();
            }
            LOGGER.info("[run] [ShutdownHooker run success].");
        } catch (Exception e) {
            LOGGER.error("[run] [ShutdownHooker run error:{}]", ExceptionUtils.getStackTrace(e));
        }
    }
}
